<?php

namespace Whf\LazyBrick\Console;

use Encore\Admin\Console\ServiceCommand;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Whf\LazyBrick\Traits\ModelTrait;

/**
 * Description IDE tools to generate FormRequest
 *
 * IDE config
 *
 * $PhpExecutable$
 *
 * artisan GenFormRequest $FileDirRelativeToProjectRoot$ $FileNameWithoutAllExtensions$ $SelectedText$
 *
 * $ProjectFileDir$
 *
 * Class RequestCommand
 *
 * @package App\Console\Commands
 */
//class RequestCommand extends Command
class RequestCommand extends GeneratorCommand
{
    use ModelTrait;


    /**
     * The name and signature of the console command.
     * @var string
     */
    protected $signature = 'lb:make_r
                            {classPath?}
                            {className?}
                            {actionName?}
                            {--stub=}
                            {--force=}';


    private $module = '';
    private $modelPath = '';
    private $controllersPath = '';
    private $requestPath = '';

    /**
     * The console command description.
     * @var string
     */
    protected $description = 'Create Illuminate\Foundation\Http\FormRequest';


    /**
     * @var ResourceGenerator
     */
    protected $generator;

    private function configInit(){
        $this->modelPath = config("lazy-brick.namespace.model");
        $this->controllersPath = config("lazy-brick.namespace.controller");
        $this->module = config("lazy-brick.module.request");
        $this->requestPath = config("lazy-brick.namespace.request");
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //配置初始化
        $this->configInit();

        $params = $this->input->getArguments();
        $classPath = $params['classPath'];
        $className = $params['className'];
        $actionName = $params['actionName'];
        $modelName = '';
        $pattern="/(([A-Z]{1}[a-z|0-9|_]+)+)(Controller)$/U";

        if(preg_match($pattern,$className)){
            $modelName=strstr($className,"Controller",true);
        }else{
            $this->error("文件类名异常");
        }

        if(!$this->modelExists($this->formatModelName($this->modelPath."\\".$modelName)))
            return $this->error("Model not exists...");

        $this->generator = new ResourceGenerator($this->modelPath."\\".$modelName);

        //获取存取模块 Example: Wap Backend Api ...
        $fileName=$modelName.ucwords($actionName)."Request";
        $name = $this->qualifyClass($fileName);
        $path = $this->getPath($name);
        if ((! $this->hasOption('force') ||
                ! $this->option('force')) &&
            $this->alreadyExists($fileName)) {
            $this->error($fileName.' already exists!');
            return false;
        }
        $this->makeDirectory($path);

        $this->files->put($path, $this->buildClass($name));

        $this->info($fileName.' created successfully.');

    }

    /**
     * Get the default namespace for the class.
     * 重写父类的方法，当父类中调用$this->getDefaultNamespace()会执行此函数
     * 编辑器ctrl+左键 会指向父类的方法 要注意
     * @author whf <wuhangfei1314@163.com>
     * @date 2019/12/16 23:03
     * @param string $rootNamespace
     * @return array|bool|string|null
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $this->requestPath."\\".$this->module;
    }

    /**
     * Replace the namespace for the given stub.
     * @author whf <wuhangfei1314@163.com>
     * @date 2019/12/16 23:12
     * @param string $stub
     * @param string $name
     * @return $this|GeneratorCommand
     */
    protected function replaceNamespace(&$stub, $name)
    {
        $stub = str_replace(
            'DummyNamespace',
            $this->getNamespace($name),
            $stub
        );
        return $this;
    }

    /**
     * Get the stub file for the generator.
     * @author whf <wuhangfei1314@163.com>
     * @date 2019/12/16 23:11
     * @return array|bool|string|null
     */
    protected function getStub()
    {
        if($stub = $this->option('stub')){
            return $stub;
        }
        return __DIR__."/stubs/request.stub";
    }

    /**
     * 替换模板内容
     * @author whf <wuhangfei1314@163.com>
     * @date 2019/12/16 23:10
     * @param string $stub
     * @param string $name
     * @return mixed|string
     */
    protected function replaceClass($stub, $name){

        return str_replace([
            'DummyClass',
            'DummyRules',
            'DummyAttributes',
            'DummyMessage',
        ],
            [
                str_replace($this->getNamespace($name).''."\\".'', '', $name),
                $this->indentCodes($this->generator->generateRequestRules(),3),
                $this->indentCodes($this->generator->generateRequestAttributes(),3),
                $this->indentCodes($this->generator->generateRequestMessage(),3),
            ],
            $stub
        );
    }

    /**
     * 配置左侧间距，我喜欢用制表符，默认2个
     * @author whf <wuhangfei1314@163.com>
     * @date 2019/12/16 23:06
     * @param $code
     * @param $multiplier
     * @return string
     */
    protected function indentCodes($code,$multiplier=2){
        $indent = str_repeat("\t", $multiplier);
        return rtrim($indent.preg_replace("/\r\n/","\r\n{$indent}",$code));
    }
}
